<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  
  
  <title>本地图片压缩（方案一） | 一枚前端小菜鸟的博客</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <meta name="description" content="本地图片压缩场景该方法试用于任何文件上传处理的地方。 原理采用 canvas.toBlobapi实现了图片压缩功能。 功能从图片的尺寸以及分辨率双层面进行压缩处理。 方法参数   参数名 参数类型 参数含义 参数默认值    file Object 文件对象 无   type String 图片类型 image&#x2F;jpeg(or image&#x2F;webp or image&#x2F;png)   _maxWidt">
<meta property="og:type" content="article">
<meta property="og:title" content="本地图片压缩（方案一）">
<meta property="og:url" content="https://gitee.com/weiyayun1995/weiyayun1995.git/2021/04/13/%E6%9C%AC%E5%9C%B0%E5%9B%BE%E7%89%87%E5%8E%8B%E7%BC%A9%EF%BC%88%E6%96%B9%E6%A1%88%E4%B8%80%EF%BC%89/index.html">
<meta property="og:site_name" content="一枚前端小菜鸟的博客">
<meta property="og:description" content="本地图片压缩场景该方法试用于任何文件上传处理的地方。 原理采用 canvas.toBlobapi实现了图片压缩功能。 功能从图片的尺寸以及分辨率双层面进行压缩处理。 方法参数   参数名 参数类型 参数含义 参数默认值    file Object 文件对象 无   type String 图片类型 image&#x2F;jpeg(or image&#x2F;webp or image&#x2F;png)   _maxWidt">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2021-04-13T03:13:02.000Z">
<meta property="article:modified_time" content="2021-04-13T03:14:17.488Z">
<meta property="article:author" content="yywei">
<meta property="article:tag" content="菜鸟,前端,js,react,vue">
<meta name="twitter:card" content="summary">
  
    <link rel="alternate" href="/atom.xml" title="一枚前端小菜鸟的博客" type="application/atom+xml">
  
  
    <link rel="shortcut icon" href="/favicon.png">
  
  
    
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/typeface-source-code-pro@0.0.71/index.min.css">

  
  
<link rel="stylesheet" href="/css/style.css">

  
    
<link rel="stylesheet" href="/fancybox/jquery.fancybox.min.css">

  
<meta name="generator" content="Hexo 5.4.0"></head>

<body>
  <div id="container">
    <div id="wrap">
      <header id="header">
  <div id="banner"></div>
  <div id="header-outer" class="outer">
    <div id="header-title" class="inner">
      <h1 id="logo-wrap">
        <a href="/" id="logo">一枚前端小菜鸟的博客</a>
      </h1>
      
        <h2 id="subtitle-wrap">
          <a href="/" id="subtitle">yywei的遇坑记录</a>
        </h2>
      
    </div>
    <div id="header-inner" class="inner">
      <nav id="main-nav">
        <a id="main-nav-toggle" class="nav-icon"></a>
        
          <a class="main-nav-link" href="/">Home</a>
        
          <a class="main-nav-link" href="/archives">Archives</a>
        
      </nav>
      <nav id="sub-nav">
        
          <a id="nav-rss-link" class="nav-icon" href="/atom.xml" title="RSS 订阅"></a>
        
        <a id="nav-search-btn" class="nav-icon" title="搜索"></a>
      </nav>
      <div id="search-form-wrap">
        <form action="//google.com/search" method="get" accept-charset="UTF-8" class="search-form"><input type="search" name="q" class="search-form-input" placeholder="搜索"><button type="submit" class="search-form-submit">&#xF002;</button><input type="hidden" name="sitesearch" value="https://gitee.com/weiyayun1995/weiyayun1995.git"></form>
      </div>
    </div>
  </div>
</header>

      <div class="outer">
        <section id="main"><article id="post-本地图片压缩（方案一）" class="h-entry article article-type-post" itemprop="blogPost" itemscope itemtype="https://schema.org/BlogPosting">
  <div class="article-meta">
    <a href="/2021/04/13/%E6%9C%AC%E5%9C%B0%E5%9B%BE%E7%89%87%E5%8E%8B%E7%BC%A9%EF%BC%88%E6%96%B9%E6%A1%88%E4%B8%80%EF%BC%89/" class="article-date">
  <time class="dt-published" datetime="2021-04-13T03:13:02.000Z" itemprop="datePublished">2021-04-13</time>
</a>
    
  </div>
  <div class="article-inner">
    
    
      <header class="article-header">
        
  
    <h1 class="p-name article-title" itemprop="headline name">
      本地图片压缩（方案一）
    </h1>
  

      </header>
    
    <div class="e-content article-entry" itemprop="articleBody">
      
        <h2 id="本地图片压缩"><a href="#本地图片压缩" class="headerlink" title="本地图片压缩"></a>本地图片压缩</h2><h3 id="场景"><a href="#场景" class="headerlink" title="场景"></a>场景</h3><p>该方法试用于任何文件上传处理的地方。</p>
<h3 id="原理"><a href="#原理" class="headerlink" title="原理"></a>原理</h3><p>采用 <code>canvas.toBlob</code>api实现了图片压缩功能。</p>
<h3 id="功能"><a href="#功能" class="headerlink" title="功能"></a>功能</h3><p>从图片的尺寸以及分辨率双层面进行压缩处理。</p>
<h3 id="方法参数"><a href="#方法参数" class="headerlink" title="方法参数"></a>方法参数</h3><table>
<thead>
<tr>
<th>参数名</th>
<th>参数类型</th>
<th>参数含义</th>
<th>参数默认值</th>
</tr>
</thead>
<tbody><tr>
<td>file</td>
<td>Object</td>
<td>文件对象</td>
<td>无</td>
</tr>
<tr>
<td>type</td>
<td>String</td>
<td>图片类型</td>
<td>image/jpeg(or image/webp or image/png)</td>
</tr>
<tr>
<td>_maxWidth</td>
<td>Number</td>
<td>图片最大宽</td>
<td>700</td>
</tr>
<tr>
<td>_maxHeight</td>
<td>Number</td>
<td>图片最大高</td>
<td>700</td>
</tr>
<tr>
<td>quality</td>
<td>Number</td>
<td>图片质量</td>
<td>0.92 (0-1)</td>
</tr>
</tbody></table>
<p>注意：当指定<code>type</code>为<code>image/png</code>类型时，不支持分辨率压缩，只有为<code>image/jpeg</code>、<code>image/webp</code>才能分辨率压缩</p>
<h3 id="代码"><a href="#代码" class="headerlink" title="代码"></a>代码</h3><p>下面是示例代码，适当的时候可以根据实际的需求<code>ctrl+c/v</code>取舍。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@return </span>Promise 压缩图片</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">&#123;Object&#125;</span> </span>file 文件对象</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">&#123;String&#125;</span> </span>type 图片类型 默认：image/jpeg...</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">&#123;Number&#125;</span> </span>_maxWidth 图片最大宽  默认 700</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">&#123;Number&#125;</span> </span>_maxHeight 图片最大高  默认 700</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">&#123;Number&#125;</span> </span>Number 图片质量 0-1</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">export</span> <span class="function"><span class="keyword">function</span> <span class="title">zipPic</span>(<span class="params">file = [], type = <span class="string">&#x27;image/jpeg&#x27;</span>, _maxWidth = <span class="number">700</span>, _maxHeight = <span class="number">700</span>, quality = <span class="number">0.92</span></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="keyword">if</span> (file.length === <span class="number">0</span> || <span class="keyword">typeof</span> type !== <span class="string">&#x27;string&#x27;</span> || <span class="keyword">typeof</span> _maxWidth !== <span class="string">&#x27;number&#x27;</span> || <span class="keyword">typeof</span> _maxHeight !== <span class="string">&#x27;number&#x27;</span> || <span class="keyword">typeof</span> quality !== <span class="string">&#x27;number&#x27;</span>) &#123;</span><br><span class="line">            <span class="keyword">return</span> reject(<span class="literal">true</span>)</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// 压缩图片需要的一些元素和对象</span></span><br><span class="line">        <span class="keyword">let</span> reader = <span class="keyword">new</span> FileReader();</span><br><span class="line">        <span class="keyword">let</span> img = <span class="keyword">new</span> Image();</span><br><span class="line">        reader.readAsDataURL(file);</span><br><span class="line">        <span class="comment">// 文件base64化，以便获知图片原始尺寸</span></span><br><span class="line">        reader.onload = <span class="function"><span class="keyword">function</span> (<span class="params">e</span>) </span>&#123;</span><br><span class="line">            img.src = e.target.result;</span><br><span class="line">        &#125;;</span><br><span class="line">        <span class="comment">// base64地址图片加载完毕后执行</span></span><br><span class="line">        img.onload = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">            <span class="comment">// 缩放图片需要的canvas</span></span><br><span class="line">            <span class="keyword">let</span> canvas = <span class="built_in">document</span>.createElement(<span class="string">&#x27;canvas&#x27;</span>);</span><br><span class="line">            <span class="keyword">let</span> context = canvas.getContext(<span class="string">&#x27;2d&#x27;</span>);</span><br><span class="line">            <span class="comment">// 图片原始尺寸</span></span><br><span class="line">            <span class="keyword">let</span> originWidth = img.width;</span><br><span class="line">            <span class="keyword">let</span> originHeight = img.height;</span><br><span class="line">            <span class="comment">// 最大尺寸限制，可通过设置宽高来实现图片压缩程度</span></span><br><span class="line">            <span class="keyword">let</span> maxWidth = _maxWidth,</span><br><span class="line">                maxHeight = _maxHeight;</span><br><span class="line">            <span class="comment">// 目标尺寸</span></span><br><span class="line">            <span class="keyword">let</span> targetWidth = originWidth,</span><br><span class="line">                targetHeight = originHeight;</span><br><span class="line">            <span class="comment">// 图片尺寸超过600x600的限制</span></span><br><span class="line">            <span class="keyword">if</span> (originWidth &gt; maxWidth || originHeight &gt; maxHeight) &#123;</span><br><span class="line">                <span class="keyword">if</span> (originWidth / originHeight &gt; maxWidth / maxHeight) &#123;</span><br><span class="line">                    <span class="comment">// 更宽，按照宽度限定尺寸</span></span><br><span class="line">                    targetWidth = maxWidth;</span><br><span class="line">                    targetHeight = <span class="built_in">Math</span>.round(maxWidth * (originHeight / originWidth));</span><br><span class="line">                &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">                    <span class="comment">// 更高，按照高度限定尺寸</span></span><br><span class="line">                    targetHeight = maxHeight;</span><br><span class="line">                    targetWidth = <span class="built_in">Math</span>.round(maxHeight * (originWidth / originHeight));</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="comment">// canvas对图片进行缩放</span></span><br><span class="line">            canvas.width = targetWidth;</span><br><span class="line">            canvas.height = targetHeight;</span><br><span class="line">            <span class="comment">// 清除画布</span></span><br><span class="line">            context.clearRect(<span class="number">0</span>, <span class="number">0</span>, targetWidth, targetHeight);</span><br><span class="line">            <span class="comment">// 图片压缩</span></span><br><span class="line">            context.drawImage(img, <span class="number">0</span>, <span class="number">0</span>, targetWidth, targetHeight);</span><br><span class="line">            <span class="comment">// 异步方法 Bolb对象</span></span><br><span class="line">            canvas.toBlob(</span><br><span class="line">                blob =&gt; &#123;</span><br><span class="line">                    <span class="comment">// 重新转为 正常的 File 对象 让 antd Upload 接收</span></span><br><span class="line">                    <span class="keyword">let</span> newFile = <span class="keyword">new</span> File([blob], file.name, &#123; <span class="attr">type</span>: file.type &#125;);</span><br><span class="line">                    newFile.uid = file.uid;</span><br><span class="line">                    resolve(newFile);</span><br><span class="line">                &#125;,</span><br><span class="line">                type,</span><br><span class="line">                quality <span class="comment">// 图片质量</span></span><br><span class="line">            );</span><br><span class="line">        &#125;;</span><br><span class="line">    &#125;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
      
    </div>
    <footer class="article-footer">
      <a data-url="https://gitee.com/weiyayun1995/weiyayun1995.git/2021/04/13/%E6%9C%AC%E5%9C%B0%E5%9B%BE%E7%89%87%E5%8E%8B%E7%BC%A9%EF%BC%88%E6%96%B9%E6%A1%88%E4%B8%80%EF%BC%89/" data-id="ckq7mlsvk000ldgt9ezm960vx" data-title="本地图片压缩（方案一）" class="article-share-link">分享</a>
      
      
      
    </footer>
  </div>
  
    
<nav id="article-nav">
  
    <a href="/2021/04/14/%E5%9B%BE%E7%89%87%E9%A2%84%E8%A7%88%E6%8F%92%E4%BB%B6viewerjs/" id="article-nav-newer" class="article-nav-link-wrap">
      <strong class="article-nav-caption">前一篇</strong>
      <div class="article-nav-title">
        
          图片预览插件viewerjs
        
      </div>
    </a>
  
  
    <a href="/2021/04/13/%E6%9C%AC%E5%9C%B0%E5%9B%BE%E7%89%87%E5%8E%8B%E7%BC%A9%EF%BC%88%E6%96%B9%E6%A1%88%E4%BA%8C%EF%BC%89/" id="article-nav-older" class="article-nav-link-wrap">
      <strong class="article-nav-caption">后一篇</strong>
      <div class="article-nav-title">图片压缩方案</div>
    </a>
  
</nav>

  
</article>


</section>
        
          <aside id="sidebar">
  
    

  
    

  
    
  
    
  <div class="widget-wrap">
    <h3 class="widget-title">归档</h3>
    <div class="widget">
      <ul class="archive-list"><li class="archive-list-item"><a class="archive-list-link" href="/archives/2021/06/">六月 2021</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2021/05/">五月 2021</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2021/04/">四月 2021</a></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2021/03/">三月 2021</a></li></ul>
    </div>
  </div>


  
    
  <div class="widget-wrap">
    <h3 class="widget-title">最新文章</h3>
    <div class="widget">
      <ul>
        
          <li>
            <a href="/2021/06/22/js%E6%95%B0%E6%8D%AE%E7%B1%BB%E5%9E%8B%E5%8F%8A%E8%BD%AC%E6%8D%A2/">js数据类型及转换</a>
          </li>
        
          <li>
            <a href="/2021/06/18/react-hook-%E9%A1%B9%E7%9B%AE%E4%B8%AD%E5%AE%9E%E8%B7%B5/">react-hook 项目中实践</a>
          </li>
        
          <li>
            <a href="/2021/06/18/%E6%95%B0%E5%AD%97%E7%AD%BE%E5%90%8D/">数字签名</a>
          </li>
        
          <li>
            <a href="/2021/06/18/sendbeacon/">sendbeacon</a>
          </li>
        
          <li>
            <a href="/2021/06/18/js%E6%95%B0%E6%8D%AE%E7%B1%BB%E5%9E%8B%E7%9A%84%E5%88%A4%E6%96%AD/">js数据类型的判断</a>
          </li>
        
      </ul>
    </div>
  </div>

  
</aside>
        
      </div>
      <footer id="footer">
  
  <div class="outer">
    <div id="footer-info" class="inner">
      
      &copy; 2021 yywei<br>
      Powered by <a href="https://hexo.io/" target="_blank">Hexo</a>
    </div>
  </div>
</footer>

    </div>
    <nav id="mobile-nav">
  
    <a href="/" class="mobile-nav-link">Home</a>
  
    <a href="/archives" class="mobile-nav-link">Archives</a>
  
</nav>
    


<script src="/js/jquery-3.4.1.min.js"></script>



  
<script src="/fancybox/jquery.fancybox.min.js"></script>




<script src="/js/script.js"></script>





  </div>
</body>
</html>